from ..utils.crypto_utils import crypto_utils
from ..utils.crypto_utils import server_utils
from ..utils.config_reader import read_util
from ..utils.logger import logger
from ..backend.backend_user import backend_user
from .app_base import AppBase


class AppAuth(AppBase):
    def __init__(self, platform_name, app_v):
        super().__init__(platform_name, app_v)  # 调用父类的初始化方法
        # 登录用户uid
        self.app_uid = None
        # 登录用户token
        self.token = None

    def user_login(self, login_data):
        """
        用户手机号、密码登录
        """
        try:
            # 动态构建请求数据
            data_dict = login_data
            logger.info("------用户手机号密码登录------")
            # 添加其他固定字段
            data_dict.update({
                "deviceId": self.deviceid,
                "build": self.build,
                "platformName": self.platform_name,
                "appV": self.appV,
                "loginType": "UPL",
            })
            response = crypto_utils.app_post_request(
                url="/v2/books/userinfo/loginByAccountAndPwd",
                data=data_dict
            )

            if response['appData']['needGraphicVerificationCode'] == 1:
                logger.info("------获取图文验证码解锁------")
                # 验证解锁手机号获取验证码
                self.check_graphic_verification_code(login_data['loginName'])  # 使用字典传值
                # 解锁成功再次登录
                logger.info("------再次尝试用户登录流程------")
                return self.user_login(login_data)  # 传入整个字典

            # 获取当前登录用户的token
            self.token = response['appData']['userInfo']['token']
            read_util.update_data('app_token', self.token)
            # 获取当前登录用户的uid
            self.app_uid = response['appData']['userInfo']['rsNo']
            read_util.update_data('app_uid', self.app_uid)
            return response
        except Exception as e:
            server_utils.handle_exception(e, f"用户手机号{login_data['loginName']}登录失败")

    def send_sms_code_app(self, login_name):
        """
        手机号注册获取验证码
        """
        try:
            data_dict = {"loginName": login_name, "appUUId": "",
                         "deviceId": self.deviceid,
                         "build": self.build, "token": "", "platformName": self.platform_name, "appV": self.appV}
            code_response = crypto_utils.app_post_request(url="/v2/userinfo/register/sendSmsCode", data=data_dict)

            # 调用获取验证码，如果状态为1就进入解锁流程
            if code_response['appData']['needGraphicVerificationCode'] == 1:
                # 验证解锁手机号获取验证码
                self.check_graphic_verification_code(login_name)
                # 解锁成功再次手机获取验证码
                return self.send_sms_code_app(login_name)
            else:
                return backend_user.user_sms_code(login_name)
        except Exception as e:
            server_utils.handle_exception(e, f"手机号{login_name}获取验证码失败")

    def app_get_captcha(self):
        """
        获取图文验证码-验证码发送太多，手机号被锁时使用
        """
        try:
            data_dict = {"appUUId": "", "deviceId": self.deviceid, "build": self.build,
                         "c": self.ctime, "token": "", "platformName": self.platform_name,
                         "t": server_utils.generate_random_string(rando_name="", length=6), "appV": self.appV}
            return crypto_utils.app_post_request(url="/captcha", data=data_dict)
        except Exception as e:
            server_utils.handle_exception(e, f"获取图文验证码失败")

    def check_graphic_verification_code(self, login_name, scene="register"):
        """
        图文验证码验证解锁
        """
        # 获取图形验证码照片
        try:
            captcha_response = self.app_get_captcha()
            # 识别获取验证码
            code = server_utils.get_app_img_code(captcha_response['appData']['captchaBase64'])

            data_dict = {"loginName": login_name, "appUUId": "", "deviceId": self.deviceid,
                         "triggerType": "1", "build": self.build, "captcha": code, "c": self.ctime,
                         "token": "", "platformName": self.platform_name, "appV": self.appV}

            crypto_utils.app_post_request(url=f"/v2/userinfo/{scene}/checkGraphicVerificationCode",
                                          data=data_dict)
        except Exception as e:
            server_utils.handle_exception(e, f"图文验证码解锁失败")

    def register_app(self, register_data):
        """
        校验短信验证码，并设置密码完成注册
        """
        try:
            # 动态构建请求数据
            data_dict = register_data

            # 获取手机验证码
            logger.info("------获取手机验证码------")
            code = self.send_sms_code_app(register_data['loginName'])

            logger.info("------校验手机验证码------")
            # 添加其他固定字段
            data_dict.update({
                "deviceId": self.deviceid,
                "build": self.build,
                "platformName": self.platform_name,
                "appV": self.appV,
                "vildatorCode": code,
            })
            response = crypto_utils.app_post_request(url="/v2/books/userinfo/register/checkSmsCode", data=data_dict)

            if response['appData']['msg'] == "注册成功":
                # 　获取新注册用户的token
                self.token = response['appData']['userInfo']['token']
                read_util.update_data('app_token', self.token)
                # 获取当前登录用户的uid
                self.app_uid = response['appData']['userInfo']['rsNo']
                read_util.update_data('app_uid', self.app_uid)
                return response

        except Exception as e:
            server_utils.handle_exception(e, f"手机号{register_data['loginName']}注册失败")

    def cancel_send_sms_code(self, login_name):
        """
        注销用户，发送短信验证码
        """
        try:
            data_dict = {"appUUId": self.app_uid,
                         "ipAddress": "192.168.1.148", "deviceId": self.deviceid,
                         "token": self.token,
                         "platformName": self.platform_name, "mobilePhone": login_name, "t": self.ctime,
                         "appV": self.appV,
                         "build": self.build, "smssigncode": "43092580fpjlkasndlasnldasjdaksldh3l2323", "smsType": "7",
                         "platform": "2", "signs": "38F7C73E6CF4EFA27C6DFC5A9874BACD"}
            response = crypto_utils.app_post_request(url="/v2/userinfo/cancelUserInfo/sendSmsCode", data=data_dict)

            # 调用获取验证码，如果状态为1就进入解锁流程
            if response['appData']['needGraphicVerificationCode'] == 1:
                # 验证解锁手机号获取验证码
                self.check_graphic_verification_code(login_name, scene="cancelUserInfo")
                # 解锁后重新再发送次验证码
                self.cancel_send_sms_code(login_name)
            else:
                return response
        except Exception as e:
            server_utils.handle_exception(e, f"手机号{login_name}注销发送验证码失败")

    def user_account_cancel(self):
        """
        注销用户账号
        """
        logger.info("------用户账号注销------")
        try:
            data_dict = {"appUUId": self.app_uid,
                         "isAgreeCancelAgreement": "2", "deviceId": self.deviceid, "build": self.build,
                         "status": "3",
                         "token": self.token,
                         "platformName": self.platform_name, "appV": self.appV}
            response = crypto_utils.app_post_request(url="/v1/userInfo/cancellation", data=data_dict)
            return response
        except Exception as e:
            server_utils.handle_exception(e, f"注销用户账号失败{self.app_uid}")

    def user_logout(self, login_data):
        """
        退出用户账号
        """
        logger.info("------用户账号退登------")
        try:
            # 动态构建请求数据
            data_dict = login_data

            data_dict.update({
                "appUUId": self.app_uid,
                "isAgreeCancelAgreement": "2",
                "deviceId": self.deviceid,
                "build": self.build,
                "status": "3",
                "token": self.token,
                "platformName": self.platform_name,
                "appV": self.appV,
            })

            response = crypto_utils.app_post_request(url="/v1/userInfo/signOut", data=data_dict)
            return response
        except Exception as e:
            server_utils.handle_exception(e, f"退出用户账号失败{self.app_uid}")


app_auth = AppAuth(platform_name="ANDRIOD", app_v="BOOKS")

# if __name__ == '__main__':
#     # 登录流程
#     logger.info("登录测试开始")
#     app_auth.user_login("13900000014", "Xkb87654312")
#     logger.info("登录测试结束\n")
